<template>
  <view class="form-card">
    <text class="form-label" :class="{required: required}">{{label}}</text>
    <view class="uploader-container">
      <view class="preview-container" v-if="currentValue" @click="previewImage">
        <image :src="currentValue" class="preview-image" mode="aspectFill"></image>
        <view class="delete-btn" @click.stop="removeImage">×</view>
      </view>
      <view class="uploader-btn" @click="chooseImage" v-else>
        <text class="uploader-icon">+</text>
        <text class="uploader-text">点击上传照片</text>
      </view>
    </view>
    <view class="divider"></view>
  </view>
</template>

<script>
import config from '../config.js';

export default {
  name: 'ImageUploader',
  model: {
      prop: 'modelValue',
      event: 'update:modelValue'
    },
  props: {
    label: {
      type: String,
      required: true
    },
    modelValue: {
      type: String,
      default: ''
    },
    required: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      currentValue: this.modelValue
    }
  },
  methods: {
    async chooseImage() {
      try {
        // 1. 选择图片
        const res = await uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        });
        
        const tempFilePath = res.tempFilePaths[0];
		const fileInfo = await uni.getFileInfo({
		      filePath: tempFilePath,
		    });
		    const fileSize = fileInfo.size;
		    const MAX_SIZE = 20 * 1024 * 1024; // 20MB
		
		    if (fileSize > MAX_SIZE) {
		      uni.showToast({
		        title: '图片大小不能超过20MB',
		        icon: 'none'
		      });
		      return; // 直接返回，不执行上传
		    }
        this.currentValue = tempFilePath;
        
        // 2. 上传图片
        const uploadRes = await uni.uploadFile({
          url:  `${config.baseUrl}/upload`,
          filePath: tempFilePath,
          name: 'file',
          header: {
            'content-type': 'multipart/form-data'
          }
        });
        console.info("uploadRes is ", JSON.stringify(uploadRes))
        // 3. 处理上传结果
        if (uploadRes.statusCode === 200) {
          const data = JSON.parse(uploadRes.data);
          if (data.code === 1) {
            // 4. 更新图片URL
			console.log('图片上传成功，URL:', data.data);
            this.currentValue = data.data;
			this.$emit("update:modelValue", data.data)
          } else {
            throw new Error(data.msg || '上传失败');
          }
        } else {
          throw new Error('上传失败');
        }
      } catch (error) {
        console.error('上传图片错误:', error);
        uni.showToast({
          title: error.message || '上传失败，请重试',
          icon: 'none'
        });
        this.currentValue = '';
		this.$emit('update:modelValue', '');
      }
    },
    removeImage() {
      this.currentValue = '';
	  this.$emit('update:modelValue', '');
    },
    // 添加图片预览功能
    previewImage() {
      if (this.currentValue) {
        uni.previewImage({
          urls: [this.currentValue]
        });
      }
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(newVal) {
        console.log('ImageUploader value changed:', newVal);
        this.currentValue = newVal;
      }
    }
  }
}
</script>

<style scoped>
.form-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}

.form-label {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 30rpx;
  display: block;
}

.form-label.required::before {
  content: '*';
  color: #f44336;
  margin-right: 8rpx;
}

.divider {
  height: 1rpx;
  background: #eee;
  margin: 20rpx -30rpx 0;
}

.uploader-container {
  margin: 20rpx 0;
}

.uploader-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200rpx;
  border: 2rpx dashed #ccc;
  border-radius: 8rpx;
  background-color: #f8f8f8;
}

.uploader-icon {
  font-size: 60rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.uploader-text {
  font-size: 28rpx;
  color: #666;
}

.preview-container {
  position: relative;
  height: 200rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.delete-btn {
  position: absolute;
  top: -20rpx;
  right: -20rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #f44336;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  line-height: 36rpx;
  z-index: 1;
}
</style>
